<template>
	<view class="reserve">
		<dl>
			<dt>
				<image :src="detail.logo" mode="aspectFill"></image>
			</dt>
			<dd>{{detail.title}}</dd>
		</dl>
		<ul>
			<li style="border-bottom: 1px solid #eeeeee;padding-top: 30rpx;">
				<p style="padding: 0;border-bottom: 0;padding-bottom: 24rpx;">{{$t('pricedetails')}}</p>
				<view class="house_time bg-white">
					<view class="time_top" v-if="type==4" @click.stop="onCalendar">
						<view class="time_text">
							<p>{{start_time}}</p>
							<span>{{ $t('check.in') }}</span>
						</view>
						<view class="time_night">
							{{info.days}}{{$t('text.nights')}}
						</view>
						<view class="time_text">
							<p>{{end_time}}</p>
							<span>{{ $t('check.out') }}</span>
						</view>
					</view>
					<view class="time_top" v-if="type==1">
						<view class="time_text" @click.stop="onCalendarMonth">
							<p>{{start_time}}</p>
							<span>{{ $t('check.in') }}</span>
						</view>
						<view class="time_night" @click.stop="isSheet=true">
							{{month}}{{ $t('text.months') }}
						</view>
						<view class="time_text">
							<p>{{endDate}}</p>
							<span>{{ $t('check.out') }}</span>
						</view>
					</view>
					<!-- &&start_time -->
					<view class="time_price" v-if="type==4&&start_time">
						<view class="time_left">
							<p>{{$t('original.price')}}</p>
							<p>{{$t('property.discount')}}</p>
							<p>{{$t('clean.fee')}}</p>
							<p>{{$t('service.charge')}}</p>
							<p>{{$t('coupon.text')}}</p>
							<p style="color: #333333;font-weight: bold;">{{$t('final.payment') }}</p>
						</view>
						<image src="@/static/switch.png" mode="widthFix"></image>
						<view class="time_right">
							<p>{{info.origin_money}} EGP</p>
							<p style="color:#FF0000">-{{info.discount_money||'0'}} EGP</p>
							<p>+{{info.cleanfee||'0'}} EGP</p>
							<p>+{{info.commision_money}} EGP</p>
							<p><span style="color:#FF0000">-{{info.coupon_money||'0'}} EGP</span><span
									style="margin-left: 12rpx;"
									@click.stop="isCoupon=true">({{$t('coupon.list')}})</span></p>
							<p style="color: #333333;font-weight: bold;">{{info.actual_money}} EGP</p>
						</view>
					</view>
					<view class="time_price" v-if="type==1&&start_time">
						<view class="time_left">
							<p>monthly price</p>
							<p style="margin-top:24rpx;">assurances</p>
							<p style="margin-top:16rpx;">service fee</p>
							<p  style="margin-top:24rpx;">{{$t('coupon.text')}}</p>
							<p style="color: #333333;font-weight: bold;margin-top:20rpx;">total amount</p>
						</view>
						<image src="@/static/switch.png" mode="widthFix"></image>
						<view class="time_right">
							<p>{{months.origin_money}} EGP</p>
							<p  style="margin-top:24rpx;">+{{months.assurance_money}} EGP(1 months)</p>
							<p  style="margin-top:16rpx;">+{{months.commision_money}} EGP</p>
							<p style="margin-top:24rpx;"><span style="color:#FF0000">-{{info.coupon_money||'0'}} EGP</span><span
									style="margin-left: 12rpx;"
									@click.stop="isCoupon=true">({{$t('coupon.list')}})</span></p>
							<p style="color: #333333;font-weight: bold;margin-top:20rpx;">
								{{months.actual_money}} EGP
							</p>
						</view>
					</view>
				</view>

			</li>
			<li>
				<p>{{ $t('your.trips') }}</p>
				<view class="reserve_block">
					<view class="reserve_item">
						<view class="item_title">{{ $t('text.guests') }}</view>
						<span>{{persons}}</span>
						<font @click.stop="isPeople=true">edit</font>
					</view>
				</view>
			</li>
			<li>
				<p>{{ $t('guest.registration') }}</p>
				<view class="reserve_block">
					<view class="reserve_item">
						<view class="item_title">full name</view>
						<view class="phoneInput">
							<input type="text" v-model="name" autocomplete="off" :always-embed="true"
								:adjust-position="true" cursor-spacing="240" placeholder="Contact Name" />
						</view>
					</view>
					<view class="reserve_item">
						<view class="item_title">{{ $t('mobile.phone.number') }}</view>
						<view class="phoneInput">
							<input type="number" v-model="phone" :always-embed="true" :adjust-position="true"
								cursor-spacing="200" :placeholder="$t('mobile.phone.number')" />
						</view>
					</view>
					<view class="reserve_item">
						<view class="item_title">{{ $t('text.notes') }}</view>
						<textarea v-model="note" :placeholder="$t('text.notes')" autocomplete="off" :always-embed="true"
							:adjust-position="true" cursor-spacing="160" />
					</view>
				</view>
			</li>
		</ul>
		<button @click.stop="handleSubmit">{{ $t('submit.submitButton') }}</button>
		<u-picker :show="isPeople" :columns="people" @cancel="cancelPeople" :cancelText="$t('text.cancel')"
			confirmText="confirm" @confirm="confirmPeople"></u-picker>
		<u-calendar :show="isCalendar" title="Date selection" startText="Check-in" endText="Check Out"
			confirmText="Confirm" mode="range" @close="onCloseCalendar" @confirm="handleCalendar"></u-calendar>

		<u-calendar ref="calendar" :show="isCalendar1" title="Date selection" startText="Check-in" endText="Check Out"
			:confirmText="$t('submit.submitButton')" :formatter="formatter" mode="range" @close="onCloseCalendar1"
			@confirm="handleCalendar1"></u-calendar>
		<u-datetime-picker ref="datetimePicker" :show="isDateTime" v-model="start" :minDate="minDate"
			:cancelText="$t('text.cancel')" confirmText="Confirm" mode="date" @close="onDateClose"
			@confirm="onDateConfirm"></u-datetime-picker>
		<u-action-sheet :actions="sheetList" title="How many months would you like to rent" :show="isSheet"
			@close="isSheet=false" @select="handleSelect"></u-action-sheet>
		<u-popup :show="isCoupon" :round="10" :closeable="true" @close="isCoupon=false">
			<view class="coupon_wrap">
				<view class="coupon_title">{{ $t('coupon.text') }}</view>
				<ul v-if="couponList.length>0">
					<li class="row" :class="{'coupon_active':couponIndex == index}" v-for="(item,index) in couponList"
						:key="index" @click.stop="couponSelected(item,index)">
						<view class="coupon_left">
							<p>{{item.money}}</p>
							<span>EGP</span>
						</view>
						<view class="coupon_right">
							<span>period of validity</span>
							<p>{{item.expireDate}}</p>
						</view>
					</li>
				</ul>
				<p class="know" v-if="couponList.length<=0">No discounts available at the moment</p>
				<view class="coupon_footer row" v-if="couponList.length>0">
					<view class="concel" @click.stop="isCoupon=false">CANCEL</view>
					<view class="confirm" @click.stop="couponConfirm">CONFIRM</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getHouseDetail,
		submitReserve,
		reserveDateInfo,
		estimateRentPrice,
		estimateLongRentPrice,
		myCoupon
	} from '@/lib/service';
	import {
		showFailure,
		showMessage,
		showSuccess
	} from '@/lib/helper';
	import {
		getTodayDate,
		getNextMonthDate,
		isValidEgyptianPhoneNumber
	} from "@/utils/utils"
	export default {
		data() {
			return {
				isCalendar: false,
				isCalendar1: false,
				isCoupon: false,
				sdate: "",
				edate: "",
				nights: 0,
				month: 1,
				detail: {
					logo: "",
					title: "",
				},
				houseid: "",
				type: "",
				persons: "1",
				isPeople: false,
				isDateTime: false,
				name: "",
				phone: "",
				note: "",
				minDate: Number,
				couponList: [],
				info: {
					days: "0",
					actual_money: "0",
					cleanfee: "0",
					discount_percent: "0",
					discount_type: "0",
					origin_money: "0",
					commision_money: "0", //佣金
					settleno: "",
				},
				start_time: "",
				end_time: "",
				start: "",
				endDate: "",
				code: 1,
				list: [],
				couponIndex: 0,
				couponid: "",
				months: {
					origin_money: "0",
					assurances_money: "0",
					commision_money: "0",
					actual_money: '0',
					settleno: "",
				},
				people: [
					['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
				],
				sheetList: [{
						name: '1'
					},
					{
						name: '2'
					}, {
						name: '3'
					}, {
						name: '4'
					}, {
						name: '5'
					}, {
						name: '6'
					}, {
						name: '7'
					}, {
						name: '8'
					}, {
						name: '9'
					}, {
						name: '20'
					}, {
						name: '11'
					}, {
						name: '12'
					}, {
						name: '13'
					}, {
						name: '14'
					}, {
						name: '15'
					}, {
						name: '16'
					}, {
						name: '17'
					}, {
						name: '18'
					}, {
						name: '19'
					}, {
						name: '20'
					}, {
						name: '21'
					}, {
						name: '22'
					}, {
						name: '23'
					}, {
						name: '24'
					}
				],
				isSheet: false
			}
		},
		onLoad(options) {
			this.houseid = options.houseid;
			this.type = options.type;
			this.start_time = options.start_time || '';
			this.end_time = options.end_time || '';
			this.getData(this.houseid);
			if (this.type == 4 && this.start_time) {
				this.handleInfo()
			}
			if (this.type == 1) {
				this.handleLong()
			}
			this.handleCoupon()
		},
		methods: {
			getData(id) {
				getHouseDetail(id).then((res) => {
					this.detail = res.data;
				});
			},
			handleCoupon() {
				myCoupon().then((res) => {
					this.couponList = res.data.list || [];
					console.log('coupon/////////////', res)
				});
			},
			handleInfo() {
				let _this = this;
				let obj = {
					houseid: this.houseid,
					sdate: this.start_time,
					edate: this.end_time
				}
				if (this.couponid) {
					obj['couponid'] = String(this.couponid);
				}
				estimateRentPrice(obj).then((res) => {
					if (res.statusCode == 0) {
						_this.info = res.data;
						_this.isCalendar1 = false;
					} else {
						_this.start_time = '';
						_this.end_time = '';
						_this.info.days = '0'
					}

				});
			},
			couponConfirm() {
				this.couponid = this.couponList[this.couponIndex].id;
				if (this.type == 4 && this.start_time) {
					this.handleInfo()
				}
				if (this.type == 1) {
					this.handleLong()
				}
				this.isCoupon = false;
			},
			handleLong() {
				let _this = this;
				let obj = {
					houseid: this.houseid,
					months: this.month,
				}
				if (this.start_time) {
					obj['sdate'] = this.start_time;
					obj['edate'] = this.type == 4 ? this.end_time : this.endDate;
				}
				if (this.couponid) {
					obj['couponid'] = String(this.couponid);
				}
				if (this.start_time) {
					estimateLongRentPrice(obj).then((res) => {
						if (res.statusCode == 0) {
							_this.months = res.data;
							_this.isDateTime = false;
							_this.isSheet = false;
						}

					});
				}

			},
			onCalendarOne() {
				this.isCalendar = true;
			},
			handleCalendar(e) {
				this.sdate = e[0];
				this.edate = e[e.length - 1];
				this.isCalendar = false;
			},
			onCloseCalendar() {
				this.isCalendar = false;
			},

			confirmPeople(e) {
				this.persons = e.value[0];
				this.isPeople = false;
			},
			cancelPeople() {
				this.isPeople = false;
			},
			couponSelected(item, index) {
				this.couponIndex = index;

			},
			handleSelect(e) {
				this.month = e.name;
				this.endDate = this.calculateEndDate(this.start_time, this.month); //根据开始日期与月份计算结算日期
				this.handleLong();
				this.isSheet = false;
			},
			onCalendar() {
				let _this = this;
				let start_time = getTodayDate();
				let end_time = getNextMonthDate();
				let obj = {
					houseid: this.houseid,
					sdate: start_time,
					edate: end_time
				}
				reserveDateInfo(obj).then((res) => {
					let list = res.data.list || [];
					_this.list = list;
					this.$nextTick(() => {
						_this.$refs.calendar.setFormatter(_this.formatter)
					})
					_this.isCalendar1 = true;

				});
			},
			// 长租
			onCalendarMonth() {
				let _this = this;
				let start_time = getTodayDate();
				let date = new Date(start_time);
				// 转换为时间戳
				let timestamp = date.getTime();
				_this.minDate = timestamp;
				_this.start_time = start_time;
				_this.isDateTime = true;

			},
			onDateClose() {
				this.isDateTime = false;
			},
			timestampToDate(timestamp) {
				const today = new Date(timestamp);
				const year = today.getFullYear();
				const month = today.getMonth() + 1; // 月份是从0开始的
				const day = today.getDate();
				return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
			},
			onDateConfirm(e) {
				let _this = this;
				this.start = e.value;
				this.start_time = this.timestampToDate(this.start);
				this.endDate = this.calculateEndDate(this.start_time, this.month); //根据开始日期与月份计算结算日期
				_this.handleLong();
				this.isDateTime = false;
			},
			handleCalendar1(e) {
				let _this = this;
				this.start_time = e[0];
				this.end_time = e[e.length - 1];
				_this.handleInfo()
			},
			onCloseCalendar1() {
				this.isCalendar1 = false;
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			// 需要将对应的文案渲染到日历上
			formatter(day) {
				const date = new Date(day.date);
				const formattedDate = this.formatDate(date);
				this.list.forEach(bookedDate => {
					if (formattedDate == bookedDate.date && bookedDate.canreserve) {
						day.bottomInfo = 'available'
						day.dot = false;
						day.disabled = false;
					}
					if (formattedDate == bookedDate.date && !bookedDate.canreserve) {
						day.bottomInfo = 'already booked'
						day.dot = false;
						day.disabled = true;
					}
				});
				return day
			},
			calculateEndDate(startDate, months) {
				const startDateObj = new Date(startDate);
				startDateObj.setMonth(startDateObj.getMonth() + months);
				const endDate = new Date(startDateObj.getTime() - 1); // 结束日期设置为起始日期月份的最后一天
				return endDate.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式的日期字符串
			},
			handleSubmit() {
				let _this = this;
				if (!this.start_time) {
					showMessage('Please fill in the start time of enrollment');
					return;
				}
				if (_this.type == 4 && !this.end_time) {
					showMessage('Please fill in the end time of enrollment');
					return;
				}
				if (_this.type == 1 && !this.endDate) {
					showMessage('Please fill in the end time of enrollment');
					return;
				}
				if (!this.name) {
					showMessage('Please fill in the name of the contact person');
					return;
				}
				if (!this.phone) {
					showMessage('Please provide your contact phone number');
					return;
				}
				let isPhone = isValidEgyptianPhoneNumber(this.phone);
				if (!isPhone) {
					showMessage(this.$t('message.phone.wrong'));
					return;
				}
				let data = {
					settleno: this.type == 4 ? this.info.settleno : this.months.settleno,
					persons: this.persons,
					name: this.name,
					phone: this.phone,
					note: this.note,
					actual_money: this.type == 4 ? this.info.actual_money : this.months.actual_money,
				}
				let info = JSON.stringify(data);
				uni.navigateTo({
					url: `./pay?info=${encodeURIComponent(info)}`
				});
			}
		},
	}
</script>

<style lang="scss" scoped>
	.reserve {
		padding: 30rpx;

		dl {
			display: flex;

			dt {
				image {
					width: 314rpx;
					height: 236rpx;
					background: #eeeeee;
					border-radius: 10rpx;
				}
			}

			dd {
				padding-left: 24rpx;
				font-family: Microsoft YaHei UI;
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
				margin-top: 16rpx;
			}
		}

		ul {

			// padding-bottom: 120rpx;
			li {
				p {
					padding: 30rpx 0;
					border-bottom: 1px solid #F6F6F6;
				}

				.reserve_block {
					.reserve_item {
						font-family: Microsoft YaHei UI;
						font-weight: 400;
						font-size: 26rpx;
						position: relative;
						padding: 24rpx 0;

						.phoneInput {
							width: 682rpx;
							height: 88rpx;
							background: #F3F3F3;
							border-radius: 10rpx;
							margin-top: 24rpx;

							input {
								width: 90%;
								height: 88rpx;
								padding-left: 30rpx;
								font-family: Microsoft YaHei UI;
								font-weight: 400;
								font-size: 30rpx;
								color: #333333;
							}
						}

						.item_title {
							color: #010101;
						}

						span {
							display: block;
							margin-top: 16rpx;
							color: #666666;
						}

						font {
							position: absolute;
							right: 0;
							bottom: 24rpx;
							text-decoration: underline;
						}

						textarea {

							width: 92%;
							height: 120rpx;
							background: #F3F3F3;
							margin-top: 24rpx;
							padding: 24rpx;
						}
					}
				}

				.house_time {
					margin-bottom: 36rpx;

					.time_top {
						display: flex;
						align-items: center;
						// justify-content: space-between;
						justify-content: space-around;

						.time_text {
							p {
								font-family: Microsoft YaHei UI;
								font-weight: 400;
								font-size: 28rpx;
								color: #333333;
								padding: 0;
								border-bottom: 0;
							}

							span {
								display: block;
								font-family: Microsoft YaHei UI;
								font-weight: 400;
								font-size: 24rpx;
								color: #999999;
								line-height: 13rpx;
								margin-top: 16rpx;
							}
						}

						.time_night {
							width: 130rpx;
							height: 40rpx;
							background: #FFFFFF;
							border-radius: 20rpx;
							border: 2rpx solid #036EFC;
							text-align: center;
							line-height: 40rpx;
							font-family: Microsoft YaHei UI;
							font-weight: 400;
							font-size: 22rpx;
							color: #333333;
						}
					}

					.time_price {
						display: flex;
						// justify-content: center;
						margin-top: 10px;

						.time_left {
							width: 45%;
							margin-right: 14rpx;

							p:first-child {
								margin-top: 56rpx;
							}

							p {
								padding: 0;
								border-bottom: 0;
								font-family: Microsoft YaHei UI;
								font-weight: 400;
								font-size: 24rpx;
								color: #999999;
								margin-top: 21rpx;
								text-align: right;
								line-height: 24rpx;
							}
						}

						image {
							width: 16rpx;
						}

						.time_right {
							margin-left: 14rpx;


							p:first-child {
								margin-top: 56rpx;
							}

							p {
								padding: 0;
								border-bottom: 0;
								font-family: Microsoft YaHei UI;
								font-weight: 400;
								font-size: 24rpx;
								color: #999999;
								margin-top: 21rpx;
								text-align: left;
								line-height: 24rpx;
							}
						}
					}
				}
			}
		}

		>button {
			width: 682rpx;
			height: 80rpx;
			background: #036EFC;
			box-shadow: 0rpx 0rpx 18rpx 2rpx rgba(0, 0, 0, 0.2);
			border-radius: 10rpx;
			font-family: Microsoft YaHei UI;
			font-weight: 400;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 80rpx;
			margin-bottom: 50px;
		}
	}

	.coupon_wrap {
		width: 100%;

		.coupon_title {
			text-align: center;
			padding: 38rpx 0;
		}

		ul {
			margin: 0 64rpx;

			.coupon_active {
				width: 100%;
				height: 120rpx;
				background: url("/static/coupon_selected.png") no-repeat !important;
				background-size: 100% 100% !important;
				margin-bottom: 16rpx;
			}

			li {
				width: 100%;
				height: 120rpx;
				background: url("/static/coupon_bg_01.png") no-repeat;
				background-size: 100% 100%;
				margin-bottom: 16rpx;

				.coupon_left {
					color: #ffffff;
					width: 206rpx;
					height: 120rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					span {
						font-family: Microsoft YaHei UI;
						font-weight: 400;
						font-size: 22rpx;
						margin-left: 8rpx;
						display: inline-block;
						margin-top: 12rpx;
					}
				}

				.coupon_right {
					padding-left: 20rpx;

					span {
						display: block;
						font-family: Microsoft YaHei UI;
						font-weight: 400;
						font-size: 20rpx;
						color: #999999;
					}

					p {
						padding: 0;
						font-family: Microsoft YaHei UI;
						font-weight: 400;
						font-size: 24rpx;
						color: #333333;
						margin-top: 12rpx;
					}
				}
			}
		}

		.know {
			text-align: center;
			padding: 200rpx 0;
			color: #999999;
		}

		.coupon_footer {
			margin: 40rpx 32rpx;
			justify-content: space-between;

			.confirm {
				background: #FF3C15;
				font-size: 32rpx;
			}

			view {
				width: 316rpx;
				height: 90rpx;
				background: #4980F7;
				border-radius: 45rpx;
				font-family: Microsoft YaHei UI;
				font-weight: 400;
				font-size: 32rpx;
				color: #FEFEFE;
				line-height: 90rpx;
				text-align: center;
			}

		}
	}
</style>